package top.infopub.mgr.flow.web;


import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.generic.GenericController;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.TemplateNodeService;
import top.infopub.mgr.flow.service.TemplateService;
import top.infopub.mgr.flow.vo.TemplateNodeVo;
import top.infopub.mgr.flow.vo.TemplateVo;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.flow.Template;
import top.infopub.model.flow.TemplateNode;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;


/**
 * 工作流管理
 * @author wangw
 * @version 2019年12月16日
 * @see FlowController
 * @since
 */
@Controller
@RequestMapping("/flow")
public class FlowController extends GenericController {

    @Autowired
    private TemplateService templateService;

    @Autowired
    private TemplateNodeService templateNodeService;

    /**
     * 工作流页面
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "flow/lay-flow-list";
    }

    /**
     * 列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<Template> queryDataByCondition(Template template, ParamPage paramPage) {
        if (!StringUtils.isBlank(template.getSrcBizTable())) {
            template.setSrcBizTable(template.getSrcBizTable().toUpperCase());
        }
        Page<Template> page = new Page<Template>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = templateService.queryPage(page, template);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 根据id查询放款记录详情
     * @param  放款记录Id
     * @return
     * @see
     */
    @RequestMapping("/queryById")
    public @ResponseBody ModelAndView queryById(HttpServletRequest request) {
        String id = request.getParameter("id");
        String flag = request.getParameter("flag");
        TemplateVo template = templateService.selectById(id);

        List<TemplateNodeVo> nodes =new ArrayList<>();
        TemplateVo templateFirst=template;
        for (int i = 0; i < template.getNodes().size(); i++) {
            if(haveNodeIdx(nodes,template.getNodes().get(i))){
                nodes.add(template.getNodes().get(i));
            }
        }
        templateFirst.setNodes(nodes);;

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("template", template);
        map.put("templateFirst", templateFirst);
        if (flag.equals("detail")) {//详情
            return new ModelAndView("flow/lay-flow-detail", map);
        }
        else if (flag.equals("addNode")) {//新增节点
            return new ModelAndView("flow/lay-flow-addNode", map);
        }
        return new ModelAndView("error/404", map);
    }

    public static boolean haveNodeIdx(List<TemplateNodeVo> nodes,TemplateNodeVo vo){
        for (TemplateNodeVo node : nodes) {
            Integer nodeIdx = node.getNodeIdx();
            if(nodeIdx==vo.getNodeIdx()){
                if(node.getChildList()==null){
                    List<TemplateNode> childList = new ArrayList<>();
                    node.setChildList(childList);;
                }
                node.getChildList().add(vo);
                return false;
            }
        }
        return true;
    }

    /**
     * 新增/重新提交
     * @return
     * @throws ParseException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/add")
    public @ResponseBody RspVo add(HttpServletRequest request)
        throws ParseException, IllegalAccessException, InvocationTargetException {
        String sname = request.getParameter("sname");
        String srcBizTable = request.getParameter("srcBizTable");
        String isEdit = request.getParameter("isEdit");
        String memo = request.getParameter("memo");
        String branchCode = request.getParameter("branchCode");
        if (StringUtils.isEmpty(sname) || StringUtils.isEmpty(srcBizTable)
            || StringUtils.isEmpty(isEdit)) {
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("缺少参数");
        }
        Template template = new Template();
        template.setSname(sname);
        template.setSrcBizTable(srcBizTable);
        template.setIsEdit(isEdit);
        template.setIsUsable("1");//默认为可用
        template.setBranchCode(branchCode);
        template.setMemo(memo);
        template.setAddBy(SessionUserUtils.getSessionUserId());
        template.setAddTime(new Date());

        templateService.insert(template);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "新增工作流 -模板名称:" + sname
                                                              + "，对应业务表单表名:" + srcBizTable, null);
        return RspVo.getSuccessResponse();
    }

    /**
     * 新增业务流节点
     * @param
     * @return
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/addNode")
    public @ResponseBody RspVo addNode(HttpServletRequest request) {
        String templateId = request.getParameter("templateId");
        String srcBizTable = request.getParameter("srcBizTable");
        String sname = request.getParameter("sname");
        String isEdit = request.getParameter("isEdit");
        String memo = request.getParameter("memo");
        String branchCode = request.getParameter("branchCode");
        if (StringUtils.isEmpty(templateId) || StringUtils.isEmpty(srcBizTable)
            || StringUtils.isEmpty(sname)) {
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("缺少参数");
        }
        Enumeration<String> names = request.getParameterNames();
        List<String> nodeIdxList = new ArrayList<String>();
        List<String> nodeNameList = new ArrayList<String>();
        List<String> checkUserIdList = new ArrayList<String>();
        List<String> nodePolicyList = new ArrayList<String>();
        List<String> routeFlagList = new ArrayList<String>();
        while (names.hasMoreElements()) {
            String name = (String)names.nextElement();
            String value = request.getParameter(name);
            if (StringUtils.isBlank(value) && !name.equals("branchCode")) {
                return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("参数不能为空");
            }
            if (name.contains("nodeIdx")) {
                nodeIdxList.add(name);
            }
            if (name.contains("nodeName")) {
                nodeNameList.add(name);
            }
            if (name.contains("chooseKey")) {
                checkUserIdList.add(name);
            }
            if (name.contains("nodePolicy")) {
                nodePolicyList.add(name);
            }
            if (name.contains("routeFlag")) {
                routeFlagList.add(name);
            }
        }
        if (CollectionUtils.isEmpty(nodeIdxList) || CollectionUtils.isEmpty(nodeNameList) || CollectionUtils.isEmpty(checkUserIdList)
            ||CollectionUtils.isEmpty(nodePolicyList) || CollectionUtils.isEmpty(routeFlagList)) {
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("至少配置一个节点");
        }
        List<TemplateNode> templateNodes = new ArrayList<TemplateNode>();
        for (String nodeIndex : nodeIdxList) {
            String endIdx=nodeIndex.split("nodeIdx")[1];
            int idx = Integer.parseInt(request.getParameter(nodeIndex));
            String nodeName = request.getParameter("nodeName" + endIdx);
            int nodePolicy = Integer.parseInt(request.getParameter("nodePolicy" + endIdx));
            int routeFlag = Integer.parseInt(request.getParameter("routeFlag" + endIdx));
            String chooseKey = request.getParameter("chooseKey" + endIdx);
            TemplateNode templateNode = new TemplateNode();
            String id = IdFactory.getUUIDUpper();
            templateNode.setId(id);
            templateNode.setTemplateId(templateId);
            templateNode.setSrcBizTable(srcBizTable);
            templateNode.setNodeIdx(idx);
            templateNode.setNodeName(nodeName);
            templateNode.setAddBy(SessionUserUtils.getSessionUserId());
            templateNode.setAddTime(new Date());
            templateNode.setNodePolicy(nodePolicy);
            templateNode.setRouteFlag(routeFlag);
            templateNode.setChooseKey(chooseKey);
            templateNodes.add(templateNode);
        }
        templateNodeService.insertByBatch(templateId, sname, srcBizTable, branchCode, isEdit,
            memo, templateNodes);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.UPDATE, "工作流新增节点 -模板id：" + templateId
                                                                 + "，模板名称：" + sname + "，对应业务表单表名:"
                                                                 + srcBizTable, null);
        return RspVo.getSuccessResponse();
    }

}
